-module(clientmanager).
-export([start/3, kill/0]).
-import(werkzeug,[logging/2, get_config_value/2, timeMilliSecond/0, to_String/1, reset_timer/3]).

start(ClientLifeTime, QueueManagerPID, Server) ->
	main(ClientLifeTime, QueueManagerPID, dict:new(), dict:new(), Server).
%register(clientmanager, spawn(fun() -> main(ClientLifeTime) end)).


main(ClientLifeTime, QueueManager, ClientMap, TimerMap, Server) ->
	receive
		{getmessages, SenderPID} ->% here is the magic, send to queuemanager
			case  dict:is_key(SenderPID, ClientMap) of
			true ->	NNR = dict:fetch(SenderPID, ClientMap), 
					TimerToReset = dict:fetch(SenderPID, TimerMap),
					ResettedTimer = werkzeug:reset_timer(TimerToReset, ClientLifeTime, {timerClient, SenderPID}),

					NewTimerMap = dict:erase(SenderPID, TimerMap),
					TimerMap2 = dict:store(SenderPID, ResettedTimer, NewTimerMap),

					QueueManager ! {getmessages, NNR, SenderPID},%Queuemanager == atom?
					main(ClientLifeTime, QueueManager, ClientMap, TimerMap2,Server);
					%Timer reset

			false -> 
				ClientMap1 = dict:store(SenderPID, 0, ClientMap),
				%Timer starten
				{ _, Timer} = timer:send_after(ClientLifeTime*1000, self(), {timerClient, SenderPID}),
				
				TimerMap1 = dict:store(SenderPID, Timer, TimerMap),
				QueueManager ! {getmessages, 0, SenderPID},
				main(ClientLifeTime, QueueManager, ClientMap1, TimerMap1,Server)
			end;
		{sendLastNNrForPID, NNR, ClientPID} when NNR > 0 ->
			ClientMap2 = dict:erase(ClientPID, ClientMap),
			ClientMap3 = dict:store(ClientPID, NNR, ClientMap2),
			main(ClientLifeTime, QueueManager, ClientMap3, TimerMap,Server);
		{timerClient, SenderPID} -> 
			ClientMap4 = erase_from_Map(SenderPID, ClientMap),
			TimerMap2 = dict:erase(SenderPID, TimerMap),
			main(ClientLifeTime, QueueManager, ClientMap4, TimerMap2, Server);
		kill -> 
			kill()
	end.

kill() -> 
	exit(self(), kill).
	%unregister(clientmanager)

erase_from_Map(ToErase, Map) ->
	Nachricht = lists:concat(["Client ", to_String(ToErase), "wird vergessen! ******\n"]),
	werkzeug:logging("../NServer.log", Nachricht),%Servername  holen
	dict:erase(ToErase, Map).
